package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.AliyunSmsUtil;
import com.itheima.reggie.utils.ValidateCodeUtils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/sendMsg")
    public R<String> getCode(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        if (StrUtil.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);
            AliyunSmsUtil.sendSms2("15256551538", code);
            session.setAttribute(phone, code);
            return R.success("发送成功");
        }
        return R.error("发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map user, HttpSession session) {
        String phone = user.get("phone").toString();
        String code = user.get("code").toString();

        Object codeInSession = session.getAttribute(phone);

        if (codeInSession != null && code.equals(codeInSession)) {
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getPhone, phone);

            User byId = userService.getOne(qw);
            //判断是否是新用户
            if (byId == null) {
                //如果是则新建对象，并save进去
                 byId = new User();
                byId.setPhone(phone);
                byId.setStatus(1);
                userService.save(byId);
                //session.setAttribute("user",user1);
                //return R.success(user1);
            }
            session.setAttribute("user",byId);
            return R.success(byId);
        }
        return R.error("登录失败");
    }
   // TODO   为什么删除session后还是可以进入页面
    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
